package com.hanthink.system.service.impl.repair;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.hanthink.common.core.domain.entity.SysDept;
import com.hanthink.common.enums.PushType;
import com.hanthink.system.mapper.SysDeptMapper;
import com.hanthink.system.service.impl.WeChatMessageServiceImpl;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.hanthink.common.constant.BusinessConstants;
import com.hanthink.common.constant.Constants;
import com.hanthink.common.core.domain.entity.SysUser;
import com.hanthink.common.core.domain.model.LoginUser;
import com.hanthink.common.exception.CustomException;
import com.hanthink.common.utils.SerialNumberUtil;
import com.hanthink.system.domain.SysSerialNumber;
import com.hanthink.system.domain.repair.Equip;
import com.hanthink.system.domain.repair.EquipFaultVo;
import com.hanthink.system.domain.repair.EquipRepairMessageVo;
import com.hanthink.system.domain.repair.EquipRepairResourceVo;
import com.hanthink.system.domain.repair.EquipRepairVo;
import com.hanthink.system.mapper.SysSerialNumberMapper;
import com.hanthink.system.mapper.repair.EquipFaultMapper;
import com.hanthink.system.mapper.repair.EquipRepairMapper;
import com.hanthink.system.service.repair.EquipRepairService;

@Service
public class EquipRepairServiceImpl implements EquipRepairService {

    @Autowired
    private EquipRepairMapper equipRepairMapper;

    @Autowired
    private SysSerialNumberMapper sysSerialNumberMapper;

    @Autowired
    private EquipFaultMapper equipFaultMapper;

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private WeChatMessageServiceImpl weChatMessageService;

    @SuppressWarnings("unchecked")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEquipReportRepairInfo(EquipRepairVo scv, LoginUser loginUser) {
        List<EquipRepairResourceVo> resourceList = new ArrayList<EquipRepairResourceVo>();
        // 保存报修信息
        try {
            // 操作用户
            SysUser user = loginUser.getUser();
            // 获取序列号
            SysSerialNumber serial = sysSerialNumberMapper.selectNextValue();
            String repairCode = SerialNumberUtil.getSerialNumber(BusinessConstants.REQUEST_FLAG,
                    serial.getNextValue(), serial.getToday());
            scv.setStatus(BusinessConstants.SELF_CHECK_STATE_PREPARE);
            scv.setRequestCode(repairCode);
            scv.setClasses(user.getClasses());
            scv.setRequestUser(user.getUserName());
            scv.setSiteKey(user.getSite());
            // 保存
            int count = equipRepairMapper.saveEquipReportRepairInfo(scv);
            // 执行状态
            if (count > 0) {
                // 保存报修文件信息
                EquipRepairResourceVo resourceVo = null;
                if (ArrayUtils.isNotEmpty(scv.getPicList())) {
                    resourceVo = new EquipRepairResourceVo();
                    String picUrl = "";
                    for (String pic : scv.getPicList()) {
                        picUrl += (pic + ";");
                    }
                    resourceVo.setFilePath(picUrl);
                    resourceVo.setRequestId(scv.getId());
                    resourceVo.setSiteKey(user.getSite());
                    resourceVo.setFileType(Constants.RESOURCE_PIC);
                    resourceList.add(resourceVo);
                }

                if (ArrayUtils.isNotEmpty(scv.getVideoList())) {
                    resourceVo = new EquipRepairResourceVo();
                    String videoUrl = "";
                    for (String video : scv.getVideoList()) {
                        videoUrl += (video + ";");
                    }
                    resourceVo.setFilePath(videoUrl);
                    resourceVo.setRequestId(scv.getId());
                    resourceVo.setSiteKey(user.getSite());
                    resourceVo.setFileType(Constants.RESOURCE_VIDEO);
                    resourceList.add(resourceVo);
                }

                if (ArrayUtils.isNotEmpty(scv.getAudioList())) {
                    resourceVo = new EquipRepairResourceVo();
                    String audioUrl = "";
                    for (String audio : scv.getAudioList()) {
                        audioUrl += (audio + ";");
                    }
                    resourceVo.setFilePath(audioUrl);
                    resourceVo.setRequestId(scv.getId());
                    resourceVo.setSiteKey(user.getSite());
                    resourceVo.setFileType(Constants.RESOURCE_AUDIO);
                    resourceList.add(resourceVo);
                }

                int result = equipRepairMapper.saveEquipRepairResourceInfo(resourceList);
                if (result < 0) {
                    throw new CustomException("隐患音视频保存失败");
                }
                // 推送消息
                String pushMessage = "隐患编号:" + "【" + repairCode + "】\n设备名称：" + scv.getEquipName() + "已生成，请确认。";
                weChatMessageService.sendMessage(user.getSite(), pushMessage, PushType.PUSH_TYPE_ONE.getValue(), null);
            } else {
                throw new CustomException("隐患单保存失败");
            }
        } catch (Exception e) {
            throw new CustomException(e.getMessage());
        }
        return true;
    }

    public void sendWeChatMessageToUser(String msg, String site, String user) {
        try {
            if (StringUtil.isEmpty(msg)) {
                return;
            }

            // 封装发送消息请求JSON
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("{");
            stringBuffer.append("\"msgtype\":" + "\"" + "text" + "\",");
            stringBuffer.append("\"text\":" + "{");
            stringBuffer.append("\"content\":" + "\"" + msg + "\"");
            stringBuffer.append(",\"mentioned_list\":" + "[\"" + user + "\"]");
            stringBuffer.append("}");
            stringBuffer.append("}");
            String json = stringBuffer.toString();

            URL postUrl = new URL("robotUrl");
            HttpURLConnection http = (HttpURLConnection) postUrl.openConnection();
            http.setRequestMethod("POST");
            http.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            http.setDoOutput(true);
            http.setDoInput(true);
            // 连接超时30秒
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
            // 读取超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000");
            http.connect();
            // 写入内容
            OutputStream outputStream = http.getOutputStream();
            outputStream.write(json.getBytes(StandardCharsets.UTF_8));
            InputStream inputStream = http.getInputStream();
            int size = inputStream.available();
            byte[] jsonBytes = new byte[size];
            inputStream.read(jsonBytes);
            String result = new String(jsonBytes, StandardCharsets.UTF_8);
            System.out.println("请求返回结果:" + result);

            // 清空输出流
            outputStream.flush();
            // 关闭输出通道
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private String JudgmentType(Long deptid) {
        String val = "";
        SysDept dept = deptMapper.selectDeptById(deptid);
        if (dept.getDeptName().contains("生产") && dept.getDeptName() != "生产与设备管理部") {
            val = "抢修";
        }
        if (dept.getDeptName().contains("设备")) {
            val = "并修";
        }
        return val;
    }

    @Override
    public List<Equip> queryEquipInfo(Equip equip) {
        return equipRepairMapper.queryEquipInfo(equip);
    }

    @Override
    public List<EquipFaultVo> queryEquipFault(Map<String, Object> params) {

        List<EquipFaultVo> faults = equipFaultMapper.queryEquipFault(params);
        if (faults.size() > 0) {
            List<EquipFaultVo> parentFaults = new ArrayList<EquipFaultVo>();
            Iterator<EquipFaultVo> iterator = faults.iterator();
            // 找出一级故障编码
            while (iterator.hasNext()) {
                EquipFaultVo info = iterator.next();
                if (info.getParentCode() == null || "".equals(info.getParentCode())) {
                    parentFaults.add(info);
                    iterator.remove();
                }

            }
            // 组合二级故障信息
            if (parentFaults.size() > 0) {
                for (EquipFaultVo parentInfo : parentFaults) {
                    List<EquipFaultVo> children = new ArrayList<EquipFaultVo>();
                    for (EquipFaultVo childInfo : faults) {
                        if (childInfo.getParentCode().equals(parentInfo.getFaultKey())) {
                            children.add(childInfo);
                        }
                    }
                    parentInfo.setChildren(children);
                }
                return parentFaults;
            }

        }

        return null;
    }

}
